<template>
  <!-- 文件上传mp4 集合 -->
  <div class="file-upload-container">
    <el-button
      @click="btnClick"
      type="primary"
      size="mini"
      v-if="String(filelist) == '' || limit != 1"
    >
      <span v-if="typeval == 'video'">上传视频</span>
      <span v-if="typeval == 'music'">上传音频</span>
      <i class="el-icon-upload el-icon--right"></i>
    </el-button>
    <el-progress
      :percentage="progressPercent"
      color="#909399"
      v-show="progressShow"
    ></el-progress>
    <!-- 动态的音频视频无法播放问题，可以通过ref去解决，这用的别一种方式 -->
    <div class="video-box" v-if="!videoing">
      <!-- 音频、视频 -->
      <div class="video-item" v-for="(item, index) in filelist" :key="index">
        <div class="video-data" v-if="typeval == 'video'">
          <video controls="controls" name="media" width="230" height="150">
            <source class="video-dom" :src="item.name" type="video/mp4" />
            您的浏览器不支持视频标签，请用谷歌浏览器打开
          </video>
        </div>
        <div class="music-data" v-if="typeval == 'music'">
          <audio controls="controls">
            <!-- name="media" width="230" height="150" -->
            <source class="music-dom" :src="item.name" type="audio/mpeg" />
            您的浏览器不支持音频标签，请用谷歌浏览器打开
          </audio>
        </div>
        <i class="el-icon-error" @click="handleRemove(index)"></i>
      </div>
    </div>
    <el-upload
      style="display: none;"
      :class="['avatar-uploader', classbox]"
      :limit="limit"
      multiple
      :action="uploadUrl"
      :before-upload="beforeAvatarUpload"
      :http-request="customUpload"
      :file-list="filelist"
      list-type="picture-card"
      :show-file-list="false"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios'
import { getQnToken } from '@/api/user'
export default {
  props: {
    filevideo: {
      type: Array,
      default: [],
    },
    limit: {
      type: Number,
      default: 1,
    },
    classbox: {
      type: String,
      default: 'video-box1',
    },
    typeval: {
      type: String,
      default: 'video', // video || music
    },
  },
  data() {
    return {
      uploadUrl: 'https://upload-z2.qiniup.com',
      uploadData: {
        key: '', // -图片名
        token: '', // -七牛token
      },
      filelist: [],
      progressShow: false,
      progressPercent: 0,
      videoing: false,
    }
  },
  created() {
    this.init()
  },
  mounted() {
    this.getQnToken()
  },
  methods: {
    init() {
      this.filelist = JSON.parse(JSON.stringify(this.filevideo))
    },
    /**
     * 获取七牛云的 token
     */
    getQnToken: function() {
      getQnToken({}).then((res) => {
        res = res.data
        if (res) {
          localStorage.setItem('qToken', JSON.stringify(res.token))
          this.uploadData.token = res.token
        }
      })
    },
    btnClick() {
      document.querySelector('.' + this.classbox + ' input').click()
    },
    /**
     * 上传 前置 判断
     */
    beforeAvatarUpload(file) {
      let fileType = file.type
      if (this.typeval == 'video' && file.name.indexOf('.mp4') !== -1) {
        let val = file.name
        let suffix = val.substring(val.lastIndexOf('.') + 1, val.length)
        this.uploadData.key =
          new Date().format('yyyyMMdd') + '/' + file.uid + '.' + suffix
        const isLt200M = file.size / 1024 / 1024 < 350
        if (!isLt200M) {
          this.$message.error('视频大小不能超过 350MB!')
          return false
        }
      } else if (this.typeval == 'video' && file.name.indexOf('.mp4') == -1) {
        this.$message.error('视频格式要求MP4!')
        return false
      }
      if (this.typeval == 'music' && file.name.indexOf('.mp3') !== -1) {
        let val1 = file.name
        let suffix1 = val1.substring(val1.lastIndexOf('.') + 1, val1.length)
        this.uploadData.key =
          new Date().format('yyyyMMdd') + '/' + file.uid + '.' + suffix1
        const isLt200M = file.size / 1024 / 1024 < 350
        if (!isLt200M) {
          this.$message.error('音频大小不能超过 350MB!')
          return false
        }
      } else if (this.typeval == 'music' && file.name.indexOf('.mp3') == -1) {
        this.$message.error('音频格式要求MP3!')
        return false
      }
    },
    // 删视频
    handleRemove(i) {
      this.videoing = true
      this.filelist.splice(i, 1)
      this.$emit('videosback', this.filelist)
      this.$nextTick(() => {
        this.videoing = false
      })
    },
    // -自定义视频上传 (为了进度条做的自定义)
    customUpload(param) {
      let file = param.file

      let form = new FormData() // 通过 FormData 对象上传文件
      form.append('file', file)
      form.append('key', this.uploadData.key)
      form.append('token', this.uploadData.token)
      this.progressShow = true
      axios
        .post(this.uploadUrl, form, {
          headers: { 'Content-Type': 'multipart/form-data' },
          onUploadProgress: (event) => {
            event.percent = Math.floor((event.loaded / event.total) * 100)
            this.progressPercent = event.percent
          },
        })
        .then(
          (res) => {
            res = res.data
            if (this.progressPercent >= 100) {
              this.progressShow = false
              this.progressPercent = 0
            }
            if (this.limit == 1) {
              this.filelist = [
                { name: this.$QNIMAGE + res.key, url: this.$QNIMAGE + res.key },
              ]
            } else {
              this.filelist.push({
                name: this.$QNIMAGE + res.key,
                url: this.$QNIMAGE + res.key,
              })
            }
            this.$emit('videosback', this.filelist)
          },
          (err) => {
            axios.defaults.uploadfile = false
          }
        )
    },
  },
}
</script>

<style lang="scss" scoped>
.file-upload-container {
  .video-box {
    // height: ;
    .video-item {
      position: relative;
      display: inline-block;
      // width: 230px;
      // height: 150px;
      margin-right: 10px;
      margin-bottom: 10px;
      cursor: pointer;
      video {
        width: 230px;
        height: 150px;
      }
      audio {
        cursor: pointer;
      }
      i.el-icon-error {
        position: absolute;
        top: -15px;
        right: -10px;
        font-size: 22px;
        color: #fe7676;
        cursor: pointer;
        z-index: -1;
        transition: all 0.3s ease;
        opacity: 0;
      }
      &:hover i.el-icon-error {
        top: -10px;
        right: -10px;
        z-index: 1;
        opacity: 1;
      }
    }
  }
  .el-progress {
    display: inline;
    margin-left: 15px;
  }
  /deep/ .el-progress-bar {
    width: 200px;
  }
}
</style>
